package cn.itsource.template;

import cn.itsource.exception.GlobalException;
import cn.itsource.pojo.bo.AccessTokenResultBo;
import cn.itsource.pojo.bo.OpenIdResultBo;
import cn.itsource.pojo.properties.MinAppProPerties;
import cn.itsource.utils.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

@Slf4j
public class WxTemplate {

    //与手机号相关的字段
    private static final String CODE_NAME = "code";
    private static final String PHONE_INFO = "phone_info";
    private static final String PHONE_NUMBER = "phoneNumber";

    private  RestTemplate restTemplate;
    private MinAppProPerties minAppProPerties;

    //构造器写入
    public WxTemplate(MinAppProPerties minAppProPerties,RestTemplate restTemplate){
        this.minAppProPerties = minAppProPerties;
        this.restTemplate = restTemplate;
    }

    /**
     * 获得openid
     * @param wxCode
     * @return
     */
    public String getOpenId(String wxCode) {

        try {
            //  2.拼接URL，组装参数，发送http请求（可以用restTemplate）
            //""https://api.weixin.qq.com/sns/jscode2session?appid="%s"&secret="%s"&js_code="%s"&grant_type=authorization_code
            // String jscode2session = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
            String jscode2sessionUrl = String.format(minAppProPerties.getOpenIdUrl(),minAppProPerties.getAppId(),minAppProPerties.getAppSecret(),wxCode);
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(jscode2sessionUrl,String.class);
            HttpStatus statusCode = responseEntity.getStatusCode();

            //判断结果
            log.debug("微信注册 : {}", statusCode,responseEntity.getBody());
            AssertUtil.isTrue(statusCode == HttpStatus.OK,"微信注册失败");
            //if(statusCode != HttpStatus.OK) {
            // throw new GlobalException("微信注册失败");
            //}

            //3.拿到结果，获取openid
            String openid = responseEntity.getBody();
            OpenIdResultBo openIdResultBo = JSON.parseObject(openid, OpenIdResultBo.class);
            return openIdResultBo.getOpenid();

        }catch (Exception e) {
            throw new GlobalException("openid获取失败");
        }



    }

    /**
     * 获取accessToken
     */
    public String getAccessToken() {
        try {
            //获取Access
            String accessTokenUrl = String.format(minAppProPerties.getAccessTokenUrl(), minAppProPerties.getAppId(), minAppProPerties.getAppSecret());
            ResponseEntity<String> tokenEntity = restTemplate.getForEntity(accessTokenUrl, String.class);
            //判断tokenEntity响应码
            HttpStatus tokenStatusCode = tokenEntity.getStatusCode();
            log.debug("获取AccessToken:{}",tokenStatusCode,tokenEntity.getBody());
            AssertUtil.isFalse(tokenStatusCode!= HttpStatus.OK,"获取access_token失败");
            //拿到token的结果
            AccessTokenResultBo accessTokenResult = JSON.parseObject(tokenEntity.getBody(), AccessTokenResultBo.class);
            return accessTokenResult.getAccess_token();
        }catch (Exception e){
            throw new GlobalException("获取access_token失败");
        }
    }



    /**
     * 获取手机号
     */

    public String getPhone(String phoneCode) {
        try{
            //获取手机号
            String phoneUrl = String.format(minAppProPerties.getPhoneUrl(),getAccessToken());

            //封装请求体；携带code
            HashMap<String,String> hashMap = new HashMap();
            hashMap.put(CODE_NAME,phoneCode);

            //设置请求头，指定为JSON
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

            //发送请求
            HttpEntity<HashMap<String,String>> httpEntity = new HttpEntity(hashMap,httpHeaders);
            ResponseEntity<String> phoneEntity = new RestTemplate().postForEntity(phoneUrl, httpEntity, String.class);

            HttpStatus phoneStatusCode = phoneEntity.getStatusCode();
            log.debug("获取Phone : {}", phoneStatusCode,phoneEntity.getBody());
            AssertUtil.isTrue(phoneStatusCode == HttpStatus.OK,"获取Phone失败");

            //拿到手机号
            JSONObject phoneJsonObject = JSON.parseObject(phoneEntity.getBody());
            JSONObject phoneInfo = phoneJsonObject.getJSONObject(PHONE_INFO);
            return phoneInfo.getString(PHONE_NUMBER);
        }catch (Exception e){
            throw new GlobalException("获取手机号失败");
        }
    }
}
